var Socket = require("socket").Socket;
var Buffer = require("binary").Buffer;

var LNHTTPClient=require("standalone/HTTPClient").LNHTTPClient;

/**
 * Class: LNHTTPServer
 */
function LNHTTPServer(options)
{
	this.clients=options.clients;
	this.comet=options.comet;
	this.app=options.app;
	system.stdout.writeLine("LNHTTPServer() - starting server at "+options.address+":"+options.port);
	this.socket=new Socket(Socket.PF_INET, Socket.SOCK_STREAM, Socket.IPPROTO_TCP);
	this.socket.setOption(Socket.SO_REUSEADDR, true);
	this.socket.bind(options.address,options.port);
	this.socket.listen(10);
}

/**
 * Method: who
 *		idiotic method. answers "LNHTTPServer"
 */
LNHTTPServer.prototype.who=function()
{
	return "LNHTTPServer";
}

/**
 * Method: action
 *		Called each time socket has anything to do
 */
LNHTTPServer.prototype.action=function()
{
	system.stdout.writeLine("LNHTTPServer.action() - some client came");
	this.clients.push(new LNHTTPClient({socket:this.socket.accept(),app:this.app,comet:this.comet,server:this}));
}

/**
 * Method: remove_client
 *		
 */
LNHTTPServer.prototype.remove_client=function(j)
{
	system.stdout.writeLine("LNHTTPServer.remove_client("+j+")");
	this.clients[j].socket.close();
	this.clients.splice(j,1);
}

/**
 * Method: remove_client_by_socket
 *		
 */
LNHTTPServer.prototype.remove_client_by_socket=function(socket)
{
	var j=0;
	while (j<this.clients.length) {
		if (this.clients[j].socket===socket) this.remove_client(j); else j++;
	}
}


exports.LNHTTPServer=LNHTTPServer;

